"""
Middleware for handling request tracing and other cross-cutting concerns
"""

from flask import request, g
import uuid
import time
import hashlib
import os

def generate_trace_id():
    """
    Generate a meaningful trace ID that can be used for request tracking.
    The trace ID will contain:
    - Timestamp (10 characters)
    - Process ID (4 characters)
    - Random component (10 characters)
    - Request hash (6 characters)
    Total: 30 characters
    """
    try:
        # Get timestamp
        timestamp = str(int(time.time()))[-10:]  # Last 10 digits of timestamp
        
        # Get process ID
        pid = format(os.getpid() % 10000, '04d')  # 4-digit process ID
        
        # Generate random component
        random_part = format(uuid.uuid4().int % (10**10), '010d')  # 10-digit random number
        
        # Generate request hash based on request details
        request_info = f"{request.method}{request.url}{request.remote_addr}"
        request_hash = hashlib.md5(request_info.encode()).hexdigest()[:6]  # First 6 chars of hash
        
        # Combine all parts
        trace_id = f"{timestamp}{pid}{random_part}{request_hash}"
        return trace_id
    except Exception:
        # Fallback to simple UUID if there's any error
        return str(uuid.uuid4())

def add_trace_id():
    """
    Middleware function to add a trace ID to each request
    """
    g.trace_id = generate_trace_id()

def before_request():
    """
    Function to be executed before each request
    """
    add_trace_id()